#!/usr/bin/python3

import json
import os
from urllib import request

print('===start===')

# filePath = '/home/liut/图片/bing-wallpaper/'
filePath = '/Users/liut/bing-wallpaper/'

if os.path.exists(filePath):
    pass
else:
    os.mkdir(filePath)

resp = request.urlopen('https://www.bing.com/HPImageArchive.aspx?format=js&n=1')
jo = json.loads(resp.read().decode('utf-8'))

# 解析出图片 URL
imgUrl = 'https://cn.bing.com' + jo.get('images')[0].get('url')
print('图片地址: ' + imgUrl)

# 从 URL 中拆分出文件名
urlList = imgUrl.split('/')
fileName = urlList[len(urlList) - 1]
print('文件名称: ' + fileName)

# 把数据写到文件
with open(filePath + fileName, 'wb') as f:
    imgF = request.urlopen(imgUrl)
    f.write(imgF.read())

# Ubuntu 设置桌面壁纸命令
# os.system("gsettings set org.gnome.desktop.background picture-uri \'file:" + filePath + fileName + "\'")

# MacOS 设置桌面壁纸命令
cmd = "osascript -e \"tell application \\\"Finder\\\" to set desktop picture to POSIX file \\\"" + filePath + fileName + "\\\"\""

print(cmd)
os.system(cmd)

print('设置完成, 文件保存在: ' + filePath + fileName)
